<?php
namespace app\wap\controller;
use think\Controller;
use think\Request;
use  app\wap\model\Weixin;
use  app\wap\Wxpay;
use  think\Session;
use think\Db;
use think\Log;
use think\Validate;

class Index2 extends Controller
{
    private  $api_url='https://d.kwibon.cn/api';//测试地址

    public function _initialize()
    {

        Log::init([
            'type'  =>  'File',
            'path'  =>  APP_PATH.'logs/'
        ]);
    }


    public function index()
    {
        header('Access-Control-Allow-Origin:*');
        $Weixin = new Weixin();
        $code = (input('code'));
        $post = request()->request();
        $log[]=[
            '授权登陆用户请求数据'=>$post,
            '授权用户请求code'=>$code,
        ];
//        Log::record($log);

        if (!empty($code)) {
            $res = $Weixin->get_access_token($code);
            $log[]=[
                '请求openid,access_token'=>$res,
            ];
            $userinfo = $Weixin->get_openid_userinfo($res['access_token'], $res['openid']);
            $log[]=[
                '授权信息'=>$res,
            ];
            $da = db('member')->where('wechat_unionid', $userinfo['unionid'])->find();
            $shu = [];
            $member_pcode = input('uid');
            if ($da == true) {
                if (empty($da['wechat_openid'])){
                    db('member')->where('wechat_unionid', $userinfo['unionid'])->update([
                        'wechat_openid'  =>$userinfo['openid']
                    ]);
                }

                $old_attachment = db("attachment")->where("id",$da['thumb'])->field("filepath")->find();
                //更新资料
                if($userinfo['headimgurl']!==$old_attachment['filepath']){
                    $new_thumb=db('attachment')->insertGetId([
                        'filepath'=>$userinfo['headimgurl'],
                    ]);
                    db('member')->where('wechat_unionid', $userinfo['unionid'])->update([
                        'thumb'  =>$new_thumb
                    ]);
                }

                if($userinfo['nickname']!==$da['member_nickname']){
                    db('member')->where('wechat_unionid', $userinfo['unionid'])->update([
                        'member_nickname'  =>$userinfo['nickname']
                    ]);
                }

                if (empty($da['token'])) {
                    if (empty($da['member_username'])){
                        $shu = [
                            'code' => 0,
                            'msg' => '第一次登陆请绑定一个账号或注册一个新的账号',
                            'data' => [
                                'openId' => $userinfo['openid'],
                                'unionId' => $userinfo['unionid'],
                                'img' => $userinfo['headimgurl'],
                                'qita'=>[
                                    'nickname' => $userinfo['nickname'],
                                    'sex' => $userinfo['sex'],
                                    'province' => $userinfo['province'],
                                    'city' => $userinfo['city'],
                                    'country' => $userinfo['country'],
                                ],
                            ]
                        ];
                        $log[]=[
                            'wap端授权登陆'=>'member_username OR token 都为空',
                        ];
                        Log::record($log);
                        return json_encode($shu);die;
                    }
                    $token = md5(md5($da['member_username']) + md5($da['wechat_unionid']) + md5(time()) . '_wap');

                    $b = db('member')->where('member_id', $da['member_id'])->update([
                        'token' => $token,
                        'token_time' => time()
                    ]);
                    if ($b == false){
                        $log[]=[
                            'wap端授权登陆'=>'token写入数据库失败',
                        ];
                        Log::record($log);
                        return json_encode(['msg' => '数据写入失败', 'code' => 101]);
                    }
                }
                $t = db('member')->where(['member_id' => $da['member_id']])->find();

                $member_pcode = input('uid');
                if (!empty($member_pcode) && $member_pcode != $t['member_id']) {
                    db('member')->where('wechat_unionid', $userinfo['unionid'])->update([
                        'member_pcode' => $member_pcode
                    ]);
                }
                //积分
                $Integral = db('integral')->select();
                //计算优惠券
                $d = db('coupondetails')
                    ->alias('a')
                    ->where('a.member_id', $t['member_id'])
                    ->join('coupon d', 'a.coupon_id=d.coupon_id')
                    ->where('a.usestatus', 0)
                    ->field('d.*,a.id,a.starttime')
                    ->select();
                $jishu = 0;
                foreach ($d as $v) {
                    if ($v['end_usetime'] < time()) {
                    } else {
                        $jishu++;
                    }
                }

                $kbxcoupon=  new Kbxcoupon();
                $dai= $kbxcoupon->usercoupon($t['member_id']);
                if (!empty($dai)){
                    $dai= json_decode($dai ,true);
                    foreach ($dai as $j){
                        if($j['locked']!=true&& $j['amount']!=0){
                            $jishu++;
                        }
                    }
                }



                $img = '';
                if (empty($da['thumb'])) {
                    $img = '';
                }else {
                    $img = db('attachment')->where('id', $da['thumb'])->find();
                    $img = $img['filepath'];
                }

                if($t['member_pcode']==1159){
                    $partner_id = 'fl';
                }else{
                    $partner_id = 'kbx';
                }

                $shu1 = [
                    'openId' => $userinfo['openid'],
                    'unionId' => $userinfo['unionid'],
                    'member_id' => $t['member_id'],
                    'member_username' => $t['member_username'],
                    'member_nickname' => $t['member_nickname'],
                    'member_integral' => $t['member_integral'],
                    'member_money' => $t['member_money'],
                    'is_apply' => $t['is_apply'],
                    'member_coupon' => $jishu,
                    'img' => $userinfo['headimgurl'],
                    'token' => $t['token'],
                    'Integral' => $Integral,
                    'partner_id'=>$partner_id
                ];
                $shu = [
                    'code' => 0,
                    'msg' => '授权成功',
                    'data' => $shu1
                ];

                $log[]=[
                    '授权成功返回数据'=>$shu1
                ];
                Log::record($log);
                return json_encode($shu)   ;
            }
            else{


                $shu = [
                    'code' => 0,
                    'msg' => '第一次登陆请绑定一个账号或注册一个新的账号',
                    'data' => [
                        'openId' => $userinfo['openid'],
                        'unionId' => $userinfo['unionid'],
                        'img' => $userinfo['headimgurl'],
                        'qita'=>[
                            'nickname' => $userinfo['nickname'],
                            'sex' => $userinfo['sex'],
                            'province' => $userinfo['province'],
                            'city' => $userinfo['city'],
                            'country' => $userinfo['country'],
                        ],

                        'member_pcode' =>$member_pcode,
                    ]
                ];
                return json_encode($shu);

            }
        }
        $url = input('url');

        $res = $Weixin->code_shouquan($url);
        return json_encode(['msg' => 'ok', 'code' => 0, 'data' => $res]);
    }

    public function kbxToken($clientId='5b4f0a2322437c15382e767d',$secret='kwiBon20l8',$timeStamp=''){
        $url = $this->api_url."/auth/login/client";
        $timeStamp = date("YmdH:i",time());
        $data['clientId'] = $clientId;
        $data['timeStamp'] = $timeStamp;
        $data['secret'] = md5($secret.$data['timeStamp']);
        $data = json_encode($data);
        list($return_code,$headers,$return_content) = $this->http_post_data($url, $data);
        $content = json_decode($return_content,true);

        if($content['token']){
            return $content['token'];
        }else{
            $this->error(__('Server error'), '', -104);
        }
    }

    public function kbxUser($unionId=''){

        $url = $this->api_url."/client/users/getUser?";

        if (!empty($unionId)){

            $url=$url."unionidOA=$unionId&";
        }
        $token = 'Bearer '.$this->kbxToken();
        $content = $this->post_data($url,'',$token);
        $content=$this->object_array(json_decode($content));

        return  $content;

    }

    function http_post_data($url, $data_string) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, TRUE);		//表示需要response header

        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                "Content-Type: application/json; charset=utf-8",
                "Content-Length: " . strlen($data_string))
        );
        ob_start();
        curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();

        //获取头部
        $header_size	= curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $headers		= substr($return_content, 0, $header_size);
        $return_content = substr($return_content,$header_size);
        //http状态码
        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        return array($return_code, $headers,$return_content);
    }
    function post_data($url, $data_string,$token) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, TRUE);		//表示需要response header

        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                "Content-Type: application/json; charset=utf-8",
                'Authorization:'.$token,
            )
        );
        ob_start();
        curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();
        //获取头部
        $header_size	= curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $headers		= substr($return_content, 0, $header_size);
        $return_content = substr($return_content,$header_size);
        //http状态码
        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        return $return_content;
    }
    function object_array($array) {
        if(is_object($array)) {
            $array = (array)$array;
        }
        if(is_array($array)) {
            foreach($array as $key=>$value) {
                $array[$key] = $this->object_array($value);
            }
        }
        return $array;
    }


}
